package com.ccys.cms.listener;

import cn.hutool.core.util.ObjectUtil;
import com.ccys.db.entity.TblBooking;
import com.ccys.db.mapper.TblBookingMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;

/**
 * redis失效key监听器
 */
@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Resource
    private TblBookingMapper tblBookingMapper;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
        setKeyspaceNotificationsConfigParameter(null);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        log.warn("==============    KEYS SUBSCRIBER    ==============");
        log.warn("               "+message.toString()+" <<WAS LOST>> ");
        log.warn("============== FROM REDIS SUBSCRIBER ==============\n");
        String expiredKey = message.toString();
        // 判断expiredKey是否以"approveMedications"开头
        if (expiredKey.startsWith("approveMedications:")) {
            // 这是批准药物之后定时十分钟之后的动作，需要去检查booking状态是否=4，符合条件则给用户发送推送消息
            // 提取bookingId
            String bookingId = expiredKey.substring("approveMedications:".length());
            if (ObjectUtil.isNotEmpty(bookingId)){
                log.info("开始检查Booking状态,ID为：{}",bookingId);
                Example bookingExample = new Example(TblBooking.class);
                bookingExample.createCriteria().andEqualTo("id",bookingExample).andEqualTo("delFlag", 0);
                TblBooking booking = tblBookingMapper.selectOneByExample(bookingExample);
                if (ObjectUtil.isNotEmpty(booking)){
                    if (booking.getStatus().equals(4)){
                        log.info("开始推送消息给用户！！");
                        //todo 推送消息 GetDeviceToPush(booking["booking_id"].ToString(), booking["mem_id"].ToString(), (int)AccountType.Member, Constants.API_Notification_Type.PATIENT.NOTIFICATION_REMAIN_TO_CONFIRM_PAYMENT);
                        log.info("消息推送成功！！");
                    }
                }else {
                    log.error("未找到这个Booking,可能状态为已删除！ID为：{}",booking);
                }
            }

        }
        //do something
    }
}
